package com.tempjob.admin.controller.sse;

import com.tempjob.admin.service.sse.SseEmitterService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;

/**
 * @author hui
 * @Date 2024/4/15 18:10
 **/
@Slf4j
@RequestMapping("/sse")
@RestController
@Api(tags = "sse")
@CrossOrigin(originPatterns = "*", methods = {RequestMethod.GET, RequestMethod.POST})
public class SseController {

    @Resource
    private SseEmitterService sseService;

    @GetMapping(value = "connect", produces = {MediaType.TEXT_EVENT_STREAM_VALUE})
    public SseEmitter connect(@RequestParam String clientId) {
        return sseService.connect(clientId);
    }

    @PostMapping(value = "/disconnect")
    public String disconnect(@RequestParam String clientId) {
        sseService.removeUser(clientId);
        return "ok";
    }


//    private static Map<String, SseEmitter> sseCache = new ConcurrentHashMap<>();


//    /**
//     * 前端传递标识，生成唯一的消息通道
//     */
//    @GetMapping(path = "subscribe", produces = {MediaType.TEXT_EVENT_STREAM_VALUE})
//    @LogIgore
//    public SseEmitter push(@RequestParam String clientId) throws IOException {
//        // 超时时间设置为3s，用于演示客户端自动重连
//        SseEmitter sseEmitter = new SseEmitter(7200000L);
//        // 设置前端的重试时间为1s
//        sseEmitter.send(SseEmitter.event().reconnectTime(1000).data("ok!"));
//        sseCache.put(clientId, sseEmitter);
//        System.out.println("add " + clientId);
//        sseEmitter.onTimeout(() -> {
//            System.out.println(clientId + "超时");
//            sseCache.remove(clientId);
//        });
//        sseEmitter.onCompletion(()->{
//            try {
//                sseEmitter.send(SseEmitter.event().reconnectTime(1000).data("connect!"));
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
//        });
//        sseEmitter.onCompletion(() -> System.out.println("完成！！！"));
//        return sseEmitter;
//    }
//
//    /**
//     * 根据标识传递信息
//     */
//    @GetMapping(path = "push")
//    public String push(@RequestParam String clientId, @RequestParam String content) throws IOException {
//        SseEmitter sseEmitter = sseCache.get(clientId);
//        if (sseEmitter != null) {
//            sseEmitter.send(content);
//        }
//        return "over";
//    }
//
//    /**
//     * 根据标识移除SseEmitter
//     */
//    @GetMapping(path = "over")
//    public String over(@RequestParam String clientId) {
//        SseEmitter sseEmitter = sseCache.get(clientId);
//        if (sseEmitter != null) {
//            sseEmitter.complete();
//            sseCache.remove(clientId);
//        }
//        return "over";
//    }


}
